#pragma once 
#include <iostream>
#include <string>
#include <string.h>
#include <functional>
#include <unordered_map>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "err.h"
#include "Ringqueue.hpp"
#include "lock.hpp"
#include "Thread.hpp"
#define gnum 1024

using namespace std;
namespace cwq_server{

    const static uint16_t default_port = 8080;
    using func_t =function<string(string)>;
class udpServer{
  public:
        udpServer(uint16_t port = default_port):  _port(port)
        {
            std::cout << "server addr: "  << " : " << _port << std::endl;
            pthread_mutex_init(&lock, nullptr);

            p = new Thread(1, std::bind(&udpServer::Recv, this));
            c = new Thread(1, std::bind(&udpServer::Broadcast, this));
        }
        void InitServer()
        {
            // 1. 创建socket接口，打开网络文件
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if(_sockfd < 0)
            {
                std::cerr << "create socket error: " << strerror(errno) << std::endl;
                exit(SOCKET_ERR);
            }
            std::cout << "create socket success: " << _sockfd << std::endl; //3

            // 2. 填充sockaddr_in结构体变量
            struct sockaddr_in local;  // 定义一个结构体，用来填充IP地址和port
            bzero(&local, sizeof(local));

            local.sin_family = AF_INET; //PF_INET
            local.sin_port = htons(_port);   
            // inet_addr: 1,2
            // 1. 字符串风格的IP地址，转换成为4字节int, "1.1.1.1" -> uint32_t -> 能不能强制类型转换呢？不能，这里要转化
            // 2. 需要将主机序列转化成为网络序列
            //3.云服务器，或者一款服务器，一般不要指明某一个确定的IP
            local.sin_addr.s_addr = INADDR_ANY;  //让我们的udpserver在启动的时候，bind任意IP
            //与系统进行绑定
            int n=bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
            if(n < 0)
            {
                std::cerr << "bind socket error: " << strerror(errno) << std::endl;
                exit(BIND_ERR);
            }
            std::cout << "bind socket success: " << _sockfd<< std::endl; //3
            p->run();
            c->run();
        }
        void Start(){
            char buffer[gnum]; //读取数据到缓冲区
            while(true){
                //读取数据
                struct sockaddr_in peer; //用来记录发送方的端口号和IP地址
                socklen_t len=sizeof(peer);//结构体的大小
                ssize_t s= recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0,(struct sockaddr*)&peer,&len);
                if(s>0){
                    buffer[s]='\0';//字符串结束标志
                }
                else continue;
                string clientip=inet_ntoa(peer.sin_addr);
                uint16_t clientport=ntohs(peer.sin_port);//将获取端口号转成主机字节序
                string message=buffer;
                cout<<clientip<<"["<<clientport<<"]#"<<message<<endl;

                //业务处理
                //string response=_service(buffer);
                //发
                //sendto(_sockfd,response.c_str(),response.size(),0,(struct sockaddr*)&peer,sizeof(peer));
            }
        }

        void addUser(const std::string &name, const struct sockaddr_in &peer)
        {
            
            LockGuard lockguard(&lock);
            auto iter = onlineuser.find(name);
            if (iter != onlineuser.end())
                return;
            // onlineuser.insert(std::make_pair<const std::string, const struct sockaddr_in>(name, peer));
            onlineuser.insert(std::pair<const std::string, const struct sockaddr_in>(name, peer));
        }

        void Recv(){
            char buffer[1024];
            while (true)
            {
                // 收
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer); // 这里一定要写清楚，未来你传入的缓冲区大小
                int n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
                if (n > 0)
                    buffer[n] = '\0';
                else
                    continue;

                std::cout << "recv done ..." << std::endl;

                // 提取client信息 -- debug
                std::string clientip = inet_ntoa(peer.sin_addr);
                uint16_t clientport = ntohs(peer.sin_port);
                std::cout << clientip << "-" << clientport << "# " << buffer << std::endl;

                // 构建一个用户，并检查
                std::string name = clientip;
                name += "-";
                name += std::to_string(clientport);
                // 如果不存在，就插入，如果存在，什么都不做
                addUser(name, peer);
                rq.push(buffer);

                // // 做业务处理
                // std::string message = service_(buffer);

                // 发
                // sendto(sock_, message.c_str(), message.size(), 0, (struct sockaddr*)&peer, sizeof(peer));
            }
        }
        void Broadcast(){
            while (true)
            {
                std::string sendstring;
                rq.pop(&sendstring);

                std::vector<struct sockaddr_in> v;
                {
                    LockGuard lockguard(&lock); 
                    for (auto user : onlineuser)
                    {
                        v.push_back(user.second);
                    }
                }
                for (auto user : v)
                {
                    // std::cout << "Broadcast message to " << user.first << sendstring << std::endl;
                    sendto(_sockfd, sendstring.c_str(), sendstring.size(), 0, (struct sockaddr *)&(user), sizeof(user));
                    std::cout << "send done ..." << sendstring << std::endl;
                }
            }
        }
     ~udpServer()
        {
            pthread_mutex_destroy(&lock);
            c->join();
            p->join();

            delete c;
            delete p;
        }
  private:
    //std::string _ip;//IP地址
    uint16_t _port;//端口号
    int _sockfd;//创建套接字返回的文件描述符
    //func_t _service;// 服务器对客户端的数据进行业务处理
    unordered_map<string,struct sockaddr_in> onlineuser;
    pthread_mutex_t lock;
    RingQueue<string> rq;
    Thread *c;
    Thread *p;
};

}



